package gui

import (
	"runtime"
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

// UIComponents UI组件管理器
type UIComponents struct {
	app *App

	// 配置相关
	configCard      *widget.Card
	configContainer *fyne.Container
	connectionInfo  *widget.Label
	configExpanded  bool

	// 文件列表相关
	fileList    *widget.List
	nameHeader  *widget.Button
	sizeHeader  *widget.Button
	timeHeader  *widget.Button
	searchEntry *widget.Entry

	// 状态相关
	progressBar *widget.ProgressBar
	statusLabel *widget.Label

	// 上传相关
	useCLIUploadCheckbox *widget.Check
	cliPathEntry         *widget.Entry
	useCLIWSLCheck       *widget.Check
	wslCommandEntry      *widget.Entry
}

// NewUIComponents 创建UI组件管理器
func NewUIComponents(app *App) *UIComponents {
	return &UIComponents{
		app: app,
	}
}

// CreateConfigArea 创建配置区域
func (ui *UIComponents) CreateConfigArea() *fyne.Container {
	// 初始化状态
	ui.configExpanded = false

	// 创建连接状态信息栏
	searchEntry := ui.createSearchEntry()
	searchWrapper := container.New(layout.NewGridWrapLayout(
		fyne.NewSize(260, searchEntry.MinSize().Height),
	), searchEntry)
	ui.connectionInfo = widget.NewLabel("未连接")
	ui.connectionInfo.Importance = widget.MediumImportance

	// 创建配置按钮
	configButton := widget.NewButtonWithIcon("配置", theme.SettingsIcon(), func() {
		ui.toggleConfig()
	})

	// 创建紧凑的状态栏
	statusBar := container.NewHBox(
		configButton,
		widget.NewSeparator(),
		widget.NewLabel("连接状态:"),
		ui.connectionInfo,
		layout.NewSpacer(),
		widget.NewLabel("搜索:"),
		searchWrapper,
	)

	// 创建配置内容
	ui.createConfigContent()

	// 主配置容器
	configArea := container.NewVBox(
		statusBar,
		ui.configContainer,
	)

	return configArea
}

// createConfigContent 创建配置内容
func (ui *UIComponents) createConfigContent() {
	config := ui.app.configManager.Config()

	secretIDEntry := widget.NewEntry()
	secretIDEntry.SetText(config.SecretID)
	secretIDEntry.SetPlaceHolder("输入 Secret ID")

	secretKeyEntry := widget.NewPasswordEntry()
	secretKeyEntry.SetText(config.SecretKey)
	secretKeyEntry.SetPlaceHolder("输入 Secret Key")

	bucketEntry := widget.NewEntry()
	bucketEntry.SetText(config.Bucket)
	bucketEntry.SetPlaceHolder("输入 Bucket 名称")

	regionEntry := widget.NewEntry()
	regionEntry.SetText(config.Region)
	regionEntry.SetPlaceHolder("输入 Region，例如 ap-shanghai")

	ui.app.useCLIUpload = config.UseCLIUpload
	ui.useCLIUploadCheckbox = widget.NewCheck("默认使用CLI上传文件", func(checked bool) {
		ui.app.useCLIUpload = checked
		ui.updateCLIControls()
	})
	ui.useCLIUploadCheckbox.SetChecked(ui.app.useCLIUpload)

	ui.cliPathEntry = widget.NewEntry()
	ui.cliPathEntry.SetText(config.CLIPath)
	ui.cliPathEntry.SetPlaceHolder("CLI 可执行文件路径（留空自动检测）")

	ui.useCLIWSLCheck = widget.NewCheck("通过 WSL 调用 CLI", func(bool) {
		ui.updateCLIControls()
	})
	ui.useCLIWSLCheck.SetChecked(config.UseCLIWSL)

	ui.wslCommandEntry = widget.NewMultiLineEntry()
	ui.wslCommandEntry.SetText(config.CLIWSLCommand)
	ui.wslCommandEntry.SetPlaceHolder("PowerShell 命令模板，使用 {} 表示文件路径")
	ui.wslCommandEntry.SetMinRowsVisible(3)

	if runtime.GOOS != "windows" {
		ui.useCLIWSLCheck.Disable()
		ui.wslCommandEntry.Disable()
	}

	saveButton := widget.NewButton("保存配置", func() {
		config.SecretID = secretIDEntry.Text
		config.SecretKey = secretKeyEntry.Text
		config.Bucket = bucketEntry.Text
		config.Region = regionEntry.Text
		config.UseCLIUpload = ui.useCLIUploadCheckbox.Checked
		config.CLIPath = strings.TrimSpace(ui.cliPathEntry.Text)
		config.UseCLIWSL = config.UseCLIUpload && ui.useCLIWSLCheck.Checked
		config.CLIWSLCommand = strings.TrimSpace(ui.wslCommandEntry.Text)

		ui.app.configManager.SetConfig(config)
		if err := ui.app.configManager.Save(); err != nil {
			ui.app.showError("保存配置失败", err)
			return
		}

		ui.app.useCLIUpload = config.UseCLIUpload
		ui.app.cliBinaryPath = ""

		ui.app.initClient()
		ui.app.showInfo("配置已保存")
	})

	testButton := widget.NewButton("测试连接", func() {
		ui.app.testConnection()
	})

	configForm := container.NewGridWithColumns(2,
		widget.NewLabel("Secret ID:"), secretIDEntry,
		widget.NewLabel("Secret Key:"), secretKeyEntry,
		widget.NewLabel("Bucket:"), bucketEntry,
		widget.NewLabel("Region:"), regionEntry,
	)

	configButtons := container.NewHBox(
		saveButton,
		testButton,
	)

	cliOptions := container.NewVBox(
		ui.useCLIUploadCheckbox,
		container.NewGridWithColumns(2,
			widget.NewLabel("CLI 路径:"), ui.cliPathEntry,
		),
		ui.useCLIWSLCheck,
		container.NewVBox(
			widget.NewLabel("WSL 命令模板（PowerShell）"),
			ui.wslCommandEntry,
		),
	)

	configContent := container.NewVBox(
		configForm,
		widget.NewSeparator(),
		cliOptions,
		widget.NewSeparator(),
		configButtons,
	)

	ui.updateCLIControls()

	ui.configCard = widget.NewCard("COS 配置", "", configContent)
	ui.configContainer = container.NewVBox(ui.configCard)
	ui.configContainer.Hide() // 默认隐藏
}

func (ui *UIComponents) updateCLIControls() {
	hasCLI := ui.useCLIUploadCheckbox != nil && ui.useCLIUploadCheckbox.Checked

	if ui.cliPathEntry != nil {
		if hasCLI {
			ui.cliPathEntry.Enable()
		} else {
			ui.cliPathEntry.Disable()
		}
	}

	if ui.useCLIWSLCheck != nil {
		if hasCLI && runtime.GOOS == "windows" {
			ui.useCLIWSLCheck.Enable()
		} else {
			if ui.useCLIWSLCheck.Checked {
				ui.useCLIWSLCheck.SetChecked(false)
			}
			ui.useCLIWSLCheck.Disable()
		}
	}

	useWSL := ui.useCLIWSLCheck != nil && ui.useCLIWSLCheck.Checked
	if ui.wslCommandEntry != nil {
		if hasCLI && useWSL && runtime.GOOS == "windows" {
			ui.wslCommandEntry.Enable()
		} else {
			ui.wslCommandEntry.Disable()
		}
	}
}

// toggleConfig 切换配置区域显示/隐藏
func (ui *UIComponents) toggleConfig() {
	if ui.configExpanded {
		ui.configContainer.Hide()
		ui.configExpanded = false
	} else {
		ui.configContainer.Show()
		ui.configExpanded = true
	}
}

// CreateDirectoryList 创建目录列表
func (ui *UIComponents) CreateDirectoryList() *widget.List {
	directoryList := widget.NewList(
		func() int { return len(ui.app.directories) },
		func() fyne.CanvasObject {
			return container.NewHBox(
				widget.NewIcon(theme.FolderIcon()),
				widget.NewLabel(""),
			)
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			containerObj := item.(*fyne.Container)
			label := containerObj.Objects[1].(*widget.Label)
			dirName := ui.app.directories[id]
			if dirName == "全部" {
				label.SetText("全部文件")
			} else {
				label.SetText(strings.Title(dirName))
			}
		},
	)

	directoryList.OnSelected = func(id widget.ListItemID) {
		selectedDir := ui.app.directories[id]
		if selectedDir == "全部" {
			ui.app.currentDir = ""
		} else {
			ui.app.currentDir = selectedDir
		}
		ui.app.refreshFileList()
	}

	return directoryList
}

// CreateFilePanel 创建文件面板
func (ui *UIComponents) CreateFilePanel() *fyne.Container {
	// 操作按钮栏
	buttonBar := ui.createButtonBar()

	// 文件列表
	ui.createFileList()

	// 排序头部
	listHeader := ui.createSortHeaders()

	// 使用Scroll容器包装文件列表
	fileListScroll := container.NewScroll(ui.fileList)
	fileListScroll.SetMinSize(fyne.NewSize(0, 400))

	// 文件面板容器
	fileListContainer := container.NewBorder(
		container.NewVBox(buttonBar, widget.NewSeparator(), listHeader), // 顶部
		nil,            // 底部
		nil,            // 左侧
		nil,            // 右侧
		fileListScroll, // 中心区域
	)

	return fileListContainer
}

// createButtonBar 创建按钮栏
func (ui *UIComponents) createButtonBar() *fyne.Container {
	uploadButton := widget.NewButtonWithIcon("上传文件", theme.ContentAddIcon(), func() {
		ui.app.showUploadDialog()
	})

	downloadButton := widget.NewButtonWithIcon("下载文件", theme.DownloadIcon(), func() {
		ui.app.downloadSelectedFile()
	})

	deleteButton := widget.NewButtonWithIcon("删除文件", theme.DeleteIcon(), func() {
		ui.app.deleteSelectedFile()
	})

	copyLinkButton := widget.NewButtonWithIcon("复制链接", theme.ContentCopyIcon(), func() {
		ui.app.copyLinkToClipboard()
	})

	copyMarkdownButton := widget.NewButtonWithIcon("复制Markdown", theme.ContentCopyIcon(), func() {
		ui.app.copyMarkdownLinkToClipboard()
	})

	refreshButton := widget.NewButtonWithIcon("刷新", theme.ViewRefreshIcon(), func() {
		ui.app.refreshFileList()
	})

	return container.NewHBox(
		uploadButton,
		downloadButton,
		deleteButton,
		widget.NewSeparator(),
		copyLinkButton,
		copyMarkdownButton,
		widget.NewSeparator(),
		refreshButton,
	)
}

// createSearchEntry 创建搜索框
func (ui *UIComponents) createSearchEntry() *widget.Entry {
	ui.searchEntry = widget.NewEntry()
	ui.searchEntry.SetPlaceHolder("搜索文件...")
	ui.searchEntry.OnChanged = func(text string) {
		ui.app.setSearchKeyword(text)
	}
	return ui.searchEntry
}

// createFileList 创建文件列表
func (ui *UIComponents) createFileList() {
	ui.fileList = widget.NewList(
		func() int { return len(ui.app.files) },
		func() fyne.CanvasObject {
			return container.NewHBox(
				widget.NewIcon(theme.DocumentIcon()),
				widget.NewLabel(""),
				widget.NewLabel(""),
				widget.NewLabel(""),
			)
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			if id >= len(ui.app.files) {
				return
			}

			file := ui.app.files[id]
			containerObj := item.(*fyne.Container)

			// 设置图标
			icon := containerObj.Objects[0].(*widget.Icon)
			ui.setFileIcon(icon, file)

			// 设置文件信息
			nameLabel := containerObj.Objects[1].(*widget.Label)
			nameLabel.SetText(file.Name)

			sizeLabel := containerObj.Objects[2].(*widget.Label)
			sizeLabel.SetText(formatFileSize(file.Size))

			timeLabel := containerObj.Objects[3].(*widget.Label)
			timeLabel.SetText(file.LastModified)
		},
	)

	ui.fileList.OnSelected = func(id widget.ListItemID) {
		ui.app.selectedFileIdx = int(id)
	}
}

// setFileIcon 设置文件图标
func (ui *UIComponents) setFileIcon(icon *widget.Icon, file *FileInfo) {
	if strings.Contains(file.Directory, "image") {
		icon.SetResource(theme.FileImageIcon())
	} else if strings.Contains(file.Directory, "document") {
		icon.SetResource(theme.FileTextIcon())
	} else if strings.Contains(file.Directory, "audio") {
		icon.SetResource(theme.FileVideoIcon())
	} else {
		icon.SetResource(theme.DocumentIcon())
	}
}

// createSortHeaders 创建排序头部
func (ui *UIComponents) createSortHeaders() *fyne.Container {
	ui.nameHeader = widget.NewButton("文件名", func() {
		ui.app.setSortBy("name")
	})
	ui.nameHeader.Importance = widget.LowImportance

	ui.sizeHeader = widget.NewButton("大小", func() {
		ui.app.setSortBy("size")
	})
	ui.sizeHeader.Importance = widget.LowImportance

	ui.timeHeader = widget.NewButton("修改时间", func() {
		ui.app.setSortBy("time")
	})
	ui.timeHeader.Importance = widget.LowImportance

	// 更新排序指示器
	ui.updateSortHeaders()

	return container.NewHBox(
		ui.nameHeader,
		ui.sizeHeader,
		ui.timeHeader,
	)
}

// updateSortHeaders 更新排序头部显示
func (ui *UIComponents) updateSortHeaders() {
	if ui.nameHeader == nil || ui.sizeHeader == nil || ui.timeHeader == nil {
		return
	}

	// 重置所有按钮文本
	ui.nameHeader.SetText("文件名")
	ui.sizeHeader.SetText("大小")
	ui.timeHeader.SetText("修改时间")

	// 为当前排序字段添加箭头指示器
	arrow := "↑"
	if !ui.app.sortAscending {
		arrow = "↓"
	}

	switch ui.app.sortBy {
	case "name":
		ui.nameHeader.SetText("文件名 " + arrow)
	case "size":
		ui.sizeHeader.SetText("大小 " + arrow)
	case "time":
		ui.timeHeader.SetText("修改时间 " + arrow)
	}
}

// CreateStatusBar 创建状态栏
func (ui *UIComponents) CreateStatusBar() *fyne.Container {
	ui.progressBar = widget.NewProgressBar()
	ui.progressBar.Hide()

	ui.statusLabel = widget.NewLabel("就绪")

	return container.NewHBox(
		ui.statusLabel,
		widget.NewSeparator(),
		ui.progressBar,
	)
}

// GetConnectionInfo 获取连接信息组件
func (ui *UIComponents) GetConnectionInfo() *widget.Label {
	return ui.connectionInfo
}

// GetFileList 获取文件列表组件
func (ui *UIComponents) GetFileList() *widget.List {
	return ui.fileList
}

// GetProgressBar 获取进度条组件
func (ui *UIComponents) GetProgressBar() *widget.ProgressBar {
	return ui.progressBar
}

// GetStatusLabel 获取状态标签组件
func (ui *UIComponents) GetStatusLabel() *widget.Label {
	return ui.statusLabel
}

// UpdateSortHeaders 对外暴露的更新排序头部方法
func (ui *UIComponents) UpdateSortHeaders() {
	ui.updateSortHeaders()
}
